<template>
  <div class="right col-2" ref="loginForm">
    <div class="box card">
      <a style="cursor: pointer">
        <img class="login-switch" v-if="showQrCode && !isShow" @click="switchLogin('1')" src="../assets/login-1.png" />
        <div class="login-switch-text" v-if="isShow" @click="switchLogin('2')">
          使用账号密码登录
        </div>
      </a>
      <div class="wx-wv" v-show="isShow">
        <div class="login-wx" style="white-space: nowrap;">扫码登录</div>
        <div id="login_container" style="text-align: center"></div>
      </div>
      <div class="amount-wv" v-if="!isShow">
        <div class="login"  style="white-space: nowrap;">账号登录</div>
        <el-form label-width="60px" ref="formRef" :rules="rules" :model="form">
          <el-form-item label="账号" prop="name">
            <el-input type="text" v-model="form.name" autocomplete="off" ref="nameRef" placeholder="请输入姓名或工号"
              @keyup.enter="searchEnterFun"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input type="password" ref="password" v-model="form.password" autocomplete="off" placeholder="请输入密码"
              @keyup.enter="searchEnterFun"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="login()">登录</el-button>
            <el-button @click="reset()">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>


<script>
import { ElButton, ElForm, ElMessage } from "element-plus";
import { vxRule } from "@/utils/validator";
import loginForm from "@/components/login.vue";
import { httpService } from "@/utils/httpService";

export default {
  name: "LoginRegister",
  created() { },
  mounted() { },
  components: { ElButton, ElForm, loginForm, ElMessage },
  data() {
    return {
      isShow: true,
      showQrCode: true,
      path: "wss://wx.zhengzhong.cn/javaApi/websocket/",
      socket: "",
      state: "",
      form: {
        name: "",
        password: "",
      },
      // 校验规则
      rules: {
        name: vxRule(true, null, "blur", "请输入账号"),
        password: vxRule(true, null, "blur", "请输入密码"),
      },
    };
  },
  methods: {
    createQrcode() {
      var element = document.createElement("script");
      element.src =
        "https://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js";
      document.body.appendChild(element);
    },
    init: function () {
      if (this.showQrCode) {
        if (typeof WebSocket === "undefined") {
          alert("您的浏览器不支持socket");
        } else {
          // 实例化socket
          this.socket = new WebSocket(this.path + this.state);
          // 监听socket连接
          this.socket.onopen = this.open;
          // 监听socket错误信息
          this.socket.onerror = this.error;
          // 监听socket消息
          this.socket.onmessage = this.getMessage;
        }
      }

    },
    open: function () {
      console.log("socket连接成功");
    },
    error: function () {
      console.log("连接错误");
    },
    getMessage: function (msg) {
      console.log("收到来自服务器的消息");
      console.log(msg.data);
      try {
        const json = JSON.parse(msg.data);
        console.log(json);

        if (json.code == 200 && this.state == json.object.state) {
          sessionStorage.removeItem("token");
          sessionStorage.removeItem("user");
          sessionStorage.setItem("token", json.object.token);
          sessionStorage.setItem("user", JSON.stringify(json.object.data));
          //进行二次登录权限验证
          let params = new FormData();
          httpService("/javaApi/login", params, "post").then((data) => {
            if (data.code == 200) {
              sessionStorage.removeItem("token");
              sessionStorage.removeItem("user");
              sessionStorage.setItem("token", data.object.token);
              sessionStorage.setItem("user", JSON.stringify(data.object.data));
              httpService("/javaApi/getAllApp", "", "get").then((data) => {
                // this.list = data;
                // console.log(this.list);
                let arr = data.filter(item => {
                  return item.appName == '宿舍管理系统'
                })
                if (arr.length === 1) {
                  this.$router.replace("dormitoryShowBefore");
                } else {
                  this.$router.replace("/");
                }
              });
              // this.$router.replace("/");
            } else {
              ElMessage.error(data.message);
            }
          });
        }
      } catch (e) {
        console.log(e);

        console.log("否");
      }
    },
    send: function (msg) {
      this.socket.send(msg);
    },
    close: function () {
      console.log("socket已经关闭");
    },
    getState() {
      var jschars = [
        "0",
        "1",
        "2",
        "3",
        "4",
        "5",
        "6",
        "7",
        "8",
        "9",
        "A",
        "B",
        "C",
        "D",
        "E",
        "F",
        "G",
        "H",
        "I",
        "J",
        "K",
        "L",
        "M",
        "N",
        "O",
        "P",
        "Q",
        "R",
        "S",
        "T",
        "U",
        "V",
        "W",
        "X",
        "Y",
        "Z",
      ];
      var res = "";
      for (var i = 0; i < 19; i++) {
        var id = Math.ceil(Math.random() * 35);
        res += jschars[id];
      }
      const state = res + new Date().valueOf();
      this.state = state;
    },
    loginWx() {
      var obj = new WxLogin({
        self_redirect: true,
        id: "login_container",
        appid: "wx32d2c23a67307ebb",
        scope: "snsapi_login",
        redirect_uri: "https://wx.zhengzhong.cn/javaApi/loginQrCallBack",
        state: this.state,
        style: "",
        href: "data:text/css;base64,LmltcG93ZXJCb3ggLnFyY29kZSB7d2lkdGg6IDIwMHB4O30KLmltcG93ZXJCb3ggLnRpdGxlIHtkaXNwbGF5OiBub25lO30KLmltcG93ZXJCb3ggLmluZm8ge3dpZHRoOiAyMDBweDt9Ci5pbXBvd2VyQm94IC5zdGF0dXN7Y29sb3I6IzQwOWVmZjt0ZXh0LWFsaWduOmNlbnRlcn0KCg==",
      });
    },
    searchEnterFun: function (e) {
      // 使用 which 和 keyCode 属性来解决兼容问题
      var keyCode = window.event ? e.keyCode : e.which;
      var val = e.target.value;
      if (keyCode == 13 && val) {
        this.login();
      }
    },
    switchLogin(id) {
      if (id == 1) {
        this.isShow = true;
        this.loginWx();

      } else {
        this.isShow = false;
      }
    },
    // 表单的重置功能
    reset() {
      this.$refs.formRef.resetFields();
    },
    login() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          let params = new FormData();
          params.append("name", this.form.name);
          params.append("password", this.form.password);
          httpService("/javaApi/login", params, "post").then((data) => {
            if (data.code == 200) {
              sessionStorage.removeItem("token");
              sessionStorage.removeItem("user");
              sessionStorage.setItem("token", data.object.token);
              sessionStorage.setItem("user", JSON.stringify(data.object.data));

              httpService("/javaApi/getAllApp", "", "get").then((data) => {
                // this.list = data;
                // console.log(this.list);
                let arr = data.filter(item => {
                  return item.appName == '宿舍管理系统'
                })
                if (arr.length === 1) {
                  this.$router.replace("dormitoryShowBefore");
                } else {
                  this.$router.replace("/");
                }
              });

              // this.$router.replace("/");
            } else {
              ElMessage.error(data.message);
            }
          });
        } else {
          return false;
        }
      });
    },
  },
};
</script>

<style>
body {
  margin: 0;
}

a {
  padding: 0px;
  background: white;
  color: #343639;
  font-size: 14px;
  display: block;
  font-weight: 700;
  text-decoration: none;
  border-radius: 0px;
}

.login-switch {
  width: 40px;
  float: right;
}

.login-switch-text {
  float: right;
  padding: 24px;
  color: #409eff;
}

.img {
  text-align: center;
  margin-top: 20px;
}

.img img {
  width: 70%;
}

.amount-wv {
  padding: 20px;
  margin-bottom: 20px;
}

.login {
  color: #409eff;
  font-size: 22px;
  padding-bottom: 40px;
  text-align: left;
}

.login-wx {
  font-size: 22px;
  padding-bottom: 40px;
  margin-left: 20px;
  margin-top: 20px;
  text-align: left; 
}

.wx-wv {
  text-align: center;
}

.wx-bottom {
  margin-top: 10px;
  margin-bottom: 40px;
}

.wx-qrcode {
  width: 200px;
  border: 1px solid #dedede;
}

.box {
  margin: 10px;
  padding: 10px;
}

@media only screen and (min-width: 1024px) {
  .col-2 {
    display: inline-block;
    *display: inline;
    *zoom: 1;
    width: 40%;
  }

  .card {
    box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
    transition: 0.3s;
    border-radius: 5px;
    width: 70%;
    padding-bottom: 50px;
    margin-top: 50px;
    background: white;
  }

  .card:hover {
    box-shadow: 0 8px 16px 0 rgba(0, 0, 0, 0.2);
  }
}
</style>